package com.briup.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.briup.cms.domain.Slideshow;
import com.briup.cms.dao.SlideshowDao;
import com.briup.cms.exception.ServiceException;
import com.briup.cms.service.ISlideshowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.cms.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author briup
 * @since 2023-03-09
 */
@Service
public class SlideshowServiceImpl implements ISlideshowService {
    @Autowired
    SlideshowDao slideshowDao;

    @Override
    public void saveOrUpdate(Slideshow slideshow) {
        //判断传入的轮播图是否为空
        if(slideshow == null)
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        //判断url是否唯一（Mybatis-Plus Lambda条件构造器去查询url)
        LambdaQueryWrapper<Slideshow> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Slideshow::getUrl,slideshow.getUrl());
        Integer count = slideshowDao.selectCount(wrapper);
        //如果url已存在 抛出异常
        if(count > 0)
            throw new ServiceException(ResultCode.DATA_EXISTED);
        //判断新增操作还是修改操作
//        slideshow.getId()=null的时候为新增
        if(slideshow.getId() == null){
            //新增
            //有没有传入url
            if(slideshow.getUrl() == null)
                throw new ServiceException(ResultCode.PARAM_NOT_COMPLETE);
            slideshow.setUploadTime(LocalDateTime.now());
            slideshowDao.insert(slideshow);
        }else{
            //修改
            //在修改的过程当中，先判断当前的轮播图是否在数据库当中
            Slideshow slideshow1 = slideshowDao.selectById(slideshow.getId());
            if(slideshow1 == null)
                throw new ServiceException(ResultCode.DATA_NONE);
            //如果存在则修改
            slideshowDao.updateById(slideshow);
        }
    }

    @Override
    public IPage<Slideshow> query(int pageNum, int pageSize, String status) {
        Page<Slideshow> page = new Page<>(pageNum,pageSize);
        LambdaQueryWrapper<Slideshow> wrapper = new LambdaQueryWrapper<>();
        if(status!=null){
            wrapper.eq(Slideshow::getStatus,status);
        }
        slideshowDao.selectPage(page,wrapper);
        return page;
    }

    @Override
    public void deleteById(Long id) {
        //调用对应删除方法
        slideshowDao.deleteById(id);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        //1、调用批量删除方法
        //2、循环调用deleteById
        for (Long id : ids) {
            this.deleteById(id);
        }
    }
}
